// stores/loading-store.ts
import { create } from 'zustand'

interface LoadingState {
  // 基础状态
  isLoading: boolean
  message: string | null

  // 加载配置
  size?: 'sm' | 'default' | 'lg'
  theme?: 'light' | 'primary' | 'secondary'

  // 加载计数（处理并发请求）
  loadingCount: number

  // Actions
  setLoading: (loading: boolean, message?: string) => void
  setLoadingMessage: (message: string) => void
  setLoadingWithConfig: (config: {
    loading: boolean
    message?: string
    size?: 'sm' | 'default' | 'lg'
    theme?: 'light' | 'primary' | 'secondary'
  }) => void
  increment: (message?: string) => void
  decrement: () => void
  reset: () => void
}

const initialState = {
  isLoading: false,
  message: null,
  size: 'default' as const,
  theme: 'primary' as const,
  loadingCount: 0,
}

export const useLoadingStore = create<LoadingState>((set) => ({
  ...initialState,

  // 设置加载状态（简单版）
  setLoading: (loading: boolean, message: string = '') =>
    set({ isLoading: loading, message }),

  // 设置加载状态（简单版）
  setLoadingMessage: (message: string = '') => {
    set({ message })
  },
  // 设置加载状态（完整配置版）
  setLoadingWithConfig: (config) =>
    set((state) => ({
      isLoading: config.loading,
      message: config.message ?? state.message,
      size: config.size ?? state.size,
      theme: config.theme ?? state.theme,
    })),

  // 增加加载计数
  increment: (message: string = '') =>
    set((state) => ({
      loadingCount: state.loadingCount + 1,
      isLoading: true,
      message: message || state.message,
    })),

  // 减少加载计数
  decrement: () =>
    set((state) => {
      const newCount = Math.max(0, state.loadingCount - 1)
      return {
        loadingCount: newCount,
        isLoading: newCount > 0,
        message: newCount === 0 ? null : state.message,
      }
    }),

  // 重置所有状态
  reset: () => set(initialState),
}))
